﻿////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// <copyright>Copyright 2008-2011 Andreas Huber Doenni</copyright>
// Distributed under the GNU General Public License version 2 (GPLv2).
// See accompanying file License.txt or copy at http://phuse.codeplex.com/license.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

namespace Phuse.Net
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.ServiceModel;
    using System.Threading.Tasks;

    using Phuse.Net.NntpTestReference;

    /// <summary>Implements an NNTP test server.</summary>
    internal sealed class NntpTestServer : IDisposable
    {
        private NntpTestServerClient client = new NntpTestServerClient(
            new BasicHttpBinding(), new EndpointAddress("http://thunderbolt:42042/PhuseNntpTestServer"));

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>Terminates the server.</summary>
        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Dispose must never throw.")]
        public void Dispose()
        {
            try
            {
                if (this.client != null)
                {
                    var clientInterface = (INntpTestServer)this.client;

                    using (var task = Task.Factory.FromAsync(
                        clientInterface.BeginStop(null, null), clientInterface.EndStop))
                    {
                        task.Wait();
                    }

                    ((ICommunicationObject)this.client).Close();
                }
            }
            catch
            {
            }
            finally
            {
                this.client = null;
            }
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        internal NntpTestServer(int port)
        {
            var clientInterface = (INntpTestServer)this.client;

            using (var task = Task.Factory.FromAsync(
                clientInterface.BeginStart(port, null, null), clientInterface.EndStart))
            {
                task.Wait();
            }
        }
    }
}
